#include "StdAfx.h"
#include "SceneNodeMotionState.hpp"
#include "..\engine\MapRenderer.hpp"
#include "..\Engine\Unit.hpp"
#include "..\engine\UnitRenderer.hpp"

namespace he
{
	UnitRenderer::UnitRenderer(UnitPtr_t const &pUnit, Ogre::Entity *pEntity, Ogre::SceneNode *pSceneNode, Ogre::Vector3 const &Scale)
		: m_pUnit(pUnit), m_pEntity(pEntity), m_pSceneNode(pSceneNode)
//		m_pMotionState(new SceneNodeMotionState(*m_pSceneNode, btTransform(btQuaternion::getIdentity(),
//			btVector3(m_pSceneNode->getPosition().x, m_pSceneNode->getPosition().y, m_pSceneNode->getPosition().z))))
	{
		// Scale the node
		m_pSceneNode->setScale(Scale);
		// Need to set position
		update_position();
//		Ogre::Vector3 const bound_box = get_bounding_box();
//		m_pCollisionShape.reset(new btBoxShape(btVector3(bound_box.x, bound_box.y, bound_box.z)));
		// Create rigid body
//		btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI_tank(1, m_pMotionState.get(), m_pCollisionShape.get(), btVector3(0,0,0));
//		m_pRigidBody.reset(new btRigidBody(groundRigidBodyCI_tank));
	}

	Ogre::Entity const &UnitRenderer::get_entity() const
	{
		return *m_pEntity;
	}

	Ogre::Vector3 const UnitRenderer::get_bounding_box() const
	{
		return get_entity().getMesh()->getBounds().getHalfSize();
	}

	void UnitRenderer::update_position()
	{
		Ogre::Vector3 const v0 = MapRenderer::tile_vertex(*m_pUnit->position(), 0);
		Ogre::Vector3 const v1 = MapRenderer::tile_vertex(*m_pUnit->position(), 1);
		// Set position as center of tile
		m_pSceneNode->setPosition(v0.x, 0, v1.z);
	}

	void UnitRenderer::start_animation( std::string const &Name, bool ControlMove, bool ControlRotation)
	{
		assert(!m_pAnimation);
		m_pAnimation.reset(new AnimationController(Name, m_pEntity, m_pSceneNode, ControlMove, ControlRotation));
	}

	void UnitRenderer::stop_animation()
	{
		m_pAnimation.reset();
	}

	void UnitRenderer::update(float TimeDelta)
	{
		// Update animation if any
		if(m_pAnimation)
		{
			m_pAnimation->update(TimeDelta);
			// Animation has ended, remove it
			if(m_pAnimation->has_ended())
				m_pAnimation.reset();
		}
	}

	Ogre::Vector3 UnitRenderer::position() const
	{
		return m_pSceneNode->getPosition();
	}

	bool UnitRenderer::is_animated() const
	{
		return m_pAnimation;
	}
} /*he*/
